﻿using IotClientApp.Server.Entity;
using IotModel;
using PluginInterface;
using System.Collections.Concurrent;

namespace IotClientApp.Server.Devices
{
    public class DeviceClientHost
    {
        private ConcurrentDictionary<string, DeviceClient> DeviceClient = new ConcurrentDictionary<string, DeviceClient>();
        public DeviceClient GetDevice(string deviceId)
        {
            DeviceClient.TryGetValue(deviceId, out DeviceClient client);
            if (client == null)
            {
                //client = new DeviceClient();
                //client.Start();
                //DeviceClient.TryAdd(deviceId, client);
                return null;
            }
            return client;
        }
        public async Task<DeviceClient> StartDevice(DeviceModel device)
        {
            DeviceClient.TryGetValue(device.DeviceId, out DeviceClient client);
            if (client == null)
            {
                client = new DeviceClient();
                await client.Start(device);
                DeviceClient.TryAdd(device.DeviceId, client);
            }
            return client;
        }
        public async Task<string> ControlPoint(string deviceId, int address, string value, DataTypeEnum dataType, EndianEnum endianEnum)
        {
            if (DeviceClient.TryGetValue(deviceId, out DeviceClient client) && client != null)
            {
                return await client.Control(address, value, dataType, endianEnum);
            }
            return "error";
        }
        public void StopDevice(string deviceId)
        {
            if (DeviceClient.TryRemove(deviceId, out DeviceClient? client) && client != null)
            {
                client.Stop(deviceId);
            }
        }
        public List<DriverReturnValueModel> GetValues(string deviceId, List<string> addrs)
        {
            DeviceClient.TryGetValue(deviceId, out DeviceClient client);
            if (client != null)
            {
                return client.GetValues(addrs);
            }
            return null;
        }
    }
}